package com.zretc.support.controller;

import com.zretc.support.entity.Online;
import com.zretc.support.service.ChatSessionService;
import com.zretc.support.tool.AjaxResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/chat")
public class ChatController {

    @Autowired
    private ChatSessionService chatSessionService;

    Logger logger = LoggerFactory.getLogger(ChatController.class);

    /**
     * 获取当前窗口用户信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public AjaxResponse info(@PathVariable("id") String id) {
        return new AjaxResponse(chatSessionService.findById(id));
    }

    /**
     * 向指定窗口推送消息
     * @param toId
     * @param online
     * @return
     */
    @PostMapping("/push/{toId}")
    public AjaxResponse push(@PathVariable("toId") String toId, @RequestBody Online online){
        try{
            WebsocketServiceEndpoint endpoint = new WebsocketServiceEndpoint();
            endpoint.sendTo(toId,online);
            return new AjaxResponse("success",200);
        }catch (Exception e){
            return new AjaxResponse(e.getMessage(),500);
        }
    }
    /**
     * 获取在线用户列表
     *
     * @return
     */
    @GetMapping("/online/list")
    public AjaxResponse onlineList(){
        return new AjaxResponse(chatSessionService.onlineList());
    }

    /**
     * 获取公共聊天消息内容
     *
     * @return
     */
    @GetMapping("/common")
    public AjaxResponse commonList(){
        return new AjaxResponse(chatSessionService.commonList());
    }

    /**
     * 获取指定用户的聊天消息内容
     *
     * @param fromId 该用户ID
     * @param toId   哪个窗口
     * @return
     */
    @GetMapping("/self/{fromId}/{toId}")
    public AjaxResponse selfList(@PathVariable("fromId") String fromId,
                                 @PathVariable("toId") String toId){
        List<Online> list = chatSessionService.selfList(fromId,toId);
        return new AjaxResponse(list);
    }

    /**
     * 退出登录
     *
     * @param id 用户ID
     * @return
     */
    @DeleteMapping("/{id}")
    public AjaxResponse logout(@PathVariable("id") String id){
        chatSessionService.delete(id);
        return new AjaxResponse();
    }

}
